<template>
  <div class="business-device">
    <!-- left -->
    <div class="fl">
      <ShopListMenu
        :has-select-all-button="true"
        :has-headquarters="true"
        title="组织架构"
        @emitShopId="emitShopId"
      />
    </div>

    <!-- right -->
    <div class="right app-main-content-box">
      <div class="flexRBC top">
        <div class="title">{{ curSelectLabel }}</div>

        <div>
          <el-button
            v-if="!$store.getters.banBtnList.includes('BTN_DEVICE_STATUA_MANAGE')"
            type="primary"
            size="medium"
            round
            style="margin-right: 10px"
            @click="openDeviceCode"
          >设备授权码
          </el-button>
          <el-dropdown
            v-if="!$store.getters.banBtnList.includes('BTN_DEVICE_ADD')"
            split-button
            type="primary"
            size="medium"
            @click="handleAdd"
          >
            新增终端
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item>
                <span style="display:block;" @click="handleImport">批量导入</span>
              </el-dropdown-item>
              <el-dropdown-item>
                <span style="display:block;" @click="handleDown">批量导出</span>
              </el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </div>

      </div>
      <!-- 搜索 -->
      <div class="list-search">
        <el-input
          v-model="filterForm[searchSelect]"
          placeholder="请输入内容"
          class="input-with-select"
          @keyup.enter.native="searchByKeyword"
        >
          <el-select slot="prepend" v-model="searchSelect" placeholder="请选择">
            <el-option
              v-for="item in selectOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-input>
        <el-button
          :loading="searchLoading"
          type="primary"
          size="medium"
          round
          icon="el-icon-search"
          @click="searchByKeyword"
        >查 询
        </el-button>
      </div>

      <!-- 表格 -->
      <div class="table">
        <el-tag type="warning" style="margin-bottom: 10px"><i class="el-icon-warning" />
          绑定状态是指该终端号已被客户端锁定，其他客户端不可重复使用该终端号；登录状态指该终端已登录使用。注意：登录该终端的用户需要是门店下的员工
        </el-tag>
        <el-table v-loading="tableLoading" :data="list" size="medium" border empty-text="暂无数据">
          <el-table-column prop="deviceName" fixed="left" label="终端名称" />
          <el-table-column prop="kdDeviceNo" label="终端编号" />
          <el-table-column prop="outDeviceNo" label="第三方编号" />
          <el-table-column prop="shopName" label="门店">
            <template slot-scope="scope">
              <span>{{ scope.row.shopId === 0 ? "总部" : scope.row.shopName }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="state" label="状态">
            <template slot-scope="scope">
              <span>{{ stateOptions[scope.row.state] }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="state" label="绑定/登录">
            <template slot-scope="scope">
              <span>
                <span v-if="scope.row.deviceStatus.bindStatus===0">未绑定</span>
                <el-tooltip popper-class="el-tooltip-theme-fresh" placement="top" effect="light">
                  <div slot="content">
                    <div v-if="scope.row.deviceStatus.bindStatus===1">
                      <div>绑定授权码：{{ scope.row.deviceStatus.bindAuthCode }}</div>
                      <div>绑定机器号：{{ scope.row.deviceStatus.bindSn }}</div>
                      <div>绑定时间：{{ scope.row.deviceStatus.bindTime }}</div>
                      <br>
                    </div>

                    <div v-if="scope.row.deviceStatus.loginStatus===1">
                      <div>登录用户ID：{{ scope.row.deviceStatus.loginUserId }}</div>
                      <div>登录用户名：{{ scope.row.deviceStatus.loginUsername }}</div>
                      <div>登录时间：{{ scope.row.deviceStatus.loginTime }}</div>
                    </div>
                  </div>
                  <span>
                    <span v-if="scope.row.deviceStatus.bindStatus===1" class="app-text-color-primary">已绑定</span>
                    <span
                      v-if="scope.row.deviceStatus.loginStatus===1"
                      class="app-text-color-primary"
                    >/&nbsp;{{ scope.row.deviceStatus.loginUsername }}</span>
                  </span>
                </el-tooltip>
              </span>
            </template>
          </el-table-column>
          <el-table-column prop="description" label="备注" />
          <el-table-column label="操作" fixed="right">
            <template slot-scope="scope">
              <el-button
                v-if="!$store.getters.banBtnList.includes('BTN_DEVICE_EDIT')"
                type="text"
                size="small"
                @click="handleEdit(scope.row)"
              >编辑
              </el-button>
              <el-button
                v-if="!$store.getters.banBtnList.includes('BTN_DEVICE_STATUA_MANAGE')"
                type="text"
                size="small"
                @click="handleStatus(scope.row)"
              >{{ scope.row.state === 0 ? "启用" : "停用" }}
              </el-button>
              <el-button
                v-if="scope.row.deviceStatus.bindStatus===1&&!$store.getters.banBtnList.includes('BTN_DEVICE_STATUA_MANAGE')"
                type="text"
                size="small"
                @click="handleUnbind(scope.row)"
              >解除绑定
              </el-button>
              <el-button
                v-if="scope.row.deviceStatus.loginStatus===1&&!$store.getters.banBtnList.includes('BTN_DEVICE_STATUA_MANAGE')"
                type="text"
                size="small"
                @click="handleLogout(scope.row)"
              >退出登录
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <!-- 分页 -->
      <pagination-direction
        v-if="paginationConfig.total!==0"
        :config="paginationConfig"
        @sizeschange="sizesChange"
        @pagechange="pageChange"
      />
    </div>

    <!-- 新增编辑弹框 -->
    <dialog-device ref="dialogDevice" :shop-id="shopId" />

    <!-- 批量上传 -->
    <dialog-upload-device ref="dialogUploadDevice" />

    <DialogDeviceCode ref="dialogDeviceCode" />

    <!-- 导出终端 -->
    <DialogShopListTree ref="dialogShopListTree" title="导出终端" @emitShopIds="emitShopIds" />

  </div>
</template>

<script>
import { listDevice, logoutDevice, unbindDevice, updateDeviceState } from '@/api/business'
import DialogDevice from './components/DialogDevice'
import DialogUploadDevice from './components/DialogUploadDevice'
import DialogDeviceCode from './components/DialogDeviceCode'
import { downBusinessDevice } from '@/api/download'

export default {
  components: {
    DialogDevice,
    DialogUploadDevice,
    DialogDeviceCode
  },
  props: {
    business: {},
    tabName: {
      type: String,
      require: true
    }
  },
  data() {
    return {
      // 配置
      // 分页配置
      paginationConfig: {
        direction: 'center', // 分页位置
        layout: 'total, sizes, prev, pager, next, jumper', // 分页类型
        pageSizes: [10, 20], // 分页pages
        total: 0,
        page: 1, // 页数-默认1
        pageSize: 10 // 每页条数-默认10
      },
      selectOptions: [
        {
          value: 'deviceName',
          label: '终端名称'
        },
        {
          value: 'kdDeviceNo',
          label: '终端编号'
        },
        {
          value: 'outDeviceNo',
          label: '第三方编号'
        }
      ],
      bindStatusOptions: ['未绑定', '已绑定'],
      stateOptions: ['已停用', '正常'],
      searchSelect: 'deviceName', // 搜索的类型
      // 状态
      tableLoading: false, // 表格loading
      searchLoading: false, // 表格loading
      // 数据
      list: [],
      curSelectLabel: '',
      shopId: null,
      shopName: '',
      // 筛选数据
      filterForm: {
        deviceName: '',
        kdDeviceNo: '',
        outDeviceNo: '',
        shopId: ''
      }
    }
  },
  watch: {
    tabName(val) {
      if (val === 'device') {
        this.fetchData(1)
      }
    },
    searchSelect(val) {
      this.filterForm.deviceName = ''
      this.filterForm.kdDeviceNo = ''
      this.filterForm.deviceName = ''
    }
  },
  mounted() {
  },
  methods: {
    /**
     * 获取数据
     */
    // 获取终端
    fetchData(
      pageNum = this.paginationConfig.page,
      pageSize = this.paginationConfig.pageSize
    ) {
      // 加入page
      this.filterForm.pageNum = pageNum
      this.filterForm.pageSize = pageSize
      const params = Object.assign({}, this.filterForm)
      // 清除多余字段
      for (const key in params) {
        if (params[key] === '' || params[key] === 'all') {
          delete params[key]
        }
      }
      if (params.shopId && params.shopId !== -1) {
        params.shopIds = [params.shopId]
      }
      delete params['shopId']
      this.tableLoading = true
      listDevice(params).then(res => {
        this.tableLoading = false
        this.searchLoading = false
        if (res.code === 0) {
          this.list = res.data.list
          this.paginationConfig.total = res.data.total
          this.paginationConfig.page = res.data.pageNum
        }
      })
    },

    // 分页sizes改变
    sizesChange(pageSize) {
      this.fetchData()
    },

    // 分页page改变
    pageChange(page) {
      this.fetchData()
    },

    /**
     * 按钮组
     */
    // 选择门店
    emitShopId(item) {
      this.shopId = item.shopId
      this.shopName = item.shopName
      this.curSelectLabel = item.shopId !== -1 ? item.shopName : '全部终端'
      this.filterForm.deviceName = ''
      this.filterForm.kdDeviceNo = ''
      this.filterForm.outDeviceNo = ''
      this.filterForm.shopId = item.shopId
      this.fetchData(1)
    },

    // 打开设备授权码
    openDeviceCode() {
      this.$refs.dialogDeviceCode.open().then(res => {
      }).finally(() => {
      })
    },

    // 新增
    handleAdd() {
      this.$refs.dialogDevice.openAdd().then(() => {
        this.fetchData()
      })
    },

    // 编辑
    handleEdit(row) {
      this.$refs.dialogDevice.openEdit(row).then(() => {
        this.fetchData()
      })
    },

    // 解除绑定
    handleUnbind(row) {
      this.$confirm(`确定解绑终端 ：${row.deviceName}?`, '温馨提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        center: true,
        roundButton: true
      }).then(() => {
        this.tableLoading = true
        const params = {
          deviceNo: row.kdDeviceNo
        }
        unbindDevice(params).then(() => {
          row.deviceStatus.bindStatus = 0
          row.deviceStatus.loginStatus = 0
          this.$notify({
            title: '成功',
            message: '解绑成功',
            type: 'success',
            duration: 2000,
            offset: 40
          })
        }).finally(() => {
          this.tableLoading = false
        })
      })
    },

    // 退出登录
    handleLogout(row) {
      this.$confirm(`确定退出登录 ：${row.deviceStatus.loginUsername} ?`, '温馨提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        center: true,
        roundButton: true
      }).then(() => {
        this.tableLoading = true
        const params = {
          deviceNo: row.kdDeviceNo
        }
        logoutDevice(params).then(() => {
          row.deviceStatus.loginStatus = 0
          this.$notify({
            title: '成功',
            message: '退出登录成功',
            type: 'success',
            duration: 2000,
            offset: 40
          })
        }).finally(() => {
          this.tableLoading = false
        })
      })
    },

    // 导出
    handleDown() {
      this.$refs.dialogShopListTree.open()
    },

    // 选择门店回调
    emitShopIds(ids) {
      if (ids.length === 0) {
        this.$alert('请至少选择一个门店导出', '提示', {
          confirmButtonText: '确定',
          center: true,
          type: 'warning',
          callback: action => {
          }
        })
      } else {
        this.$refs.dialogShopListTree.loading()
        downBusinessDevice({ shopIds: ids })
          .then(res => {
            this.$alert('数据导出中，请稍后到数据下载中心进行下载', '提示', {
              confirmButtonText: '确定',
              center: true,
              type: 'success',
              callback: action => {
              }
            })
            this.$refs.dialogShopListTree.hide()
          })
          .finally(() => {
            this.$refs.dialogShopListTree.loading(false)
          })
      }
    },

    // 打开批量上传
    handleImport() {
      this.$refs.dialogUploadDevice.open()
    },

    // 点击搜索
    searchByKeyword() {
      this.searchLoading = true
      this.fetchData(1)
    },

    // 停用 启用
    handleStatus(row) {
      const type = row.state === 0 ? '启用' : '停用'
      this.$confirm(`确定${type}终端 ${row.deviceName} ?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        center: true,
        roundButton: true
      })
        .then(() => {
          const params = {}
          params.state = row.state === 0 ? 1 : 0
          params.id = row.id
          updateDeviceState(params).then(res => {
            if (res.code === 0) {
              row.state = params.state
              this.$notify({
                title: '成功',
                message: `已${type}`,
                type: 'success',
                duration: 2000,
                offset: 40
              })
            } else {
              this.$message.error(res.msg)
            }
          })
        })
        .catch(() => {
        })
    }
  }
}
</script>
<style rel="stylesheet/scss" lang="scss" scoped>
/* 右侧表格 */
.right {
  overflow: hidden;

  .top {
    margin-bottom: 10px;

    .title{
      font-size: 18px;
      font-weight: bold;
    }
  }

  /* 搜索*/
  .list-search {
    padding-top: 10px;
    margin-bottom: 10px;

    .el-select {
      width: 120px;
    }

    .el-input {
      width: 400px;
      margin-right: 10px;
    }
  }
}
</style>
